<template>
  <div>
    <div class="ke__search">
      <el-button type="primary"
                 icon="el-icon-plus"
                 @click="onClickAdd">
        添加数据
      </el-button>
    </div>

    <div class="ke__padding ke__bgfff">
      <el-table :data="list" v-loading="loading">

        <el-table-column prop="title" label="标题"/>

        <el-table-column prop="link" label="链接"/>

        <el-table-column label="图片">
          <template slot-scope="{ row }">
            <el-image :src="row.image" style="width: 45px; height: 45px"/>
          </template>
        </el-table-column>

        <el-table-column label="是否可用" align="center">
          <template slot-scope="{ row }">
            <i :class="{
              'el-icon-check': !row.is_disabled,
              'el-icon-close': row.is_disabled,
              'disabled': true
            }"/>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="260" align="center">
          <template slot-scope="{ row, $index }">
            <el-button size="small" type="info"
                       icon="el-icon-edit"
                       @click="onClickEdit(row, $index)">编辑</el-button>

            <el-button size="small" type="danger"
                       icon="el-icon-delete" @click="onClickDelete(row, $index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <data-banner-form ref="dialog" v-model="editDialogShow"/>
  </div>
</template>

<script>
import { Vue, Component } from 'vue-property-decorator'
import Dialog from './form'
@Component({
  components: {
    [Dialog.name]: Dialog
  }
})
export default class DataBannerIndex extends Vue {
  list = []
  total = 0
  loading = true
  editDialogShow = false

  mounted () {
    this.onLoad()
  }

  // 加载列表数据
  onLoad () {
    this.loading = true
    this.$http.get('admin/banner', { type: 'index' })
      .finally(() => this.loading = false)
      .then(result => {
        this.list = result.list
        this.total = result.total
      })
  }

  onClickAdd () {
    this.editDialogShow = true
    // this.$refs.dialog.callback = (data) => {
    //   this.list.unshift({ ...data })
    // }
  }

  onClickEdit (row, index) {
    this.editDialogShow = true
    this.$refs.dialog.form = { ...row }
    this.$refs.dialog.callback = (data) => {
      this.list.splice(index, 1, { ...data })
    }
  }

  onClickDelete (item, index) {
    this.$confirm('确定要删除此项吗?')
      .then(() => {
        this.$http.delete(`admin/banner/${item.id}`)
          .then(result => {
            if (result.res_code === 0) {
              this.$message.success('删除成功')
              this.list.splice(index, 1)
            } else {
              this.$message.error('删除失败')
            }
          })
      })
  }
}
</script>

<style scoped>
  .disabled {
    color: #1e6abc;
  }
</style>
